package kz.edu.sdu.atm.server;

import java.io.File;
import java.math.BigDecimal;
import java.util.Map;

import kz.edu.sdu.atm.db.FileDbAdapter;
import kz.edu.sdu.atm.models.OperationType;
import kz.edu.sdu.atm.models.Response;
import kz.edu.sdu.atm.models.ResponseStatus;
import kz.edu.sdu.atm.models.UserDTO;

public class Server extends IServer {

	public Server() {
		storeAdapter = new FileDbAdapter(new File(STORE_FILE_NAME));
	}

	@Override
	public void auth(UserDTO user, Map<String, String> args, Response res) {
		res.set(ResponseStatus.OK, "OK");
	}

	@Override
	public void balance(UserDTO user, Map<String, String> args, Response res) {
		res.set(ResponseStatus.OK, user.getMoney()
				.toPlainString());
	}

	@Override
	public void deposit(UserDTO user, Map<String, String> args, Response res) {
		BigDecimal add = BigDecimal.ZERO;
		try{
			add = new BigDecimal(args.get(OperationType.DEPOSIT
					.toString()));
		}catch(Exception e){
			res.set(ResponseStatus.INVALID, "invalid amount specified");
			return;
		}
		user.setMoney(user.getMoney().add(add));
		storeAdapter.saveUser(user);
		res.set(ResponseStatus.OK, user.getMoney()
				.toPlainString());
	}

	@Override
	public void send(UserDTO user, Map<String, String> args, Response res) {
		BigDecimal send = BigDecimal.ZERO;
		try {
			send = new BigDecimal(args.get(OperationType.SEND.toString()));
		} catch (Exception e) {
			res.set(ResponseStatus.INVALID,
					"invalid amount specified");
			return;
		}
		String to_username = "";
		try {
			to_username = args.get("TO");
		} catch (Exception e) {
			res.set(ResponseStatus.INVALID,
					"invalid amount specified");
			return;
		}
		if (user.getMoney().compareTo(send) < 0) {
			res.set(ResponseStatus.NOPOSSIBLE, "not enough money");
			return;
		}
		UserDTO toUser = storeAdapter.getUser(to_username);
		if (toUser == null) {
			res.set(ResponseStatus.INVALID, String.format(
					"no such user: %s", to_username));
			return;
		}
		BigDecimal t = user.getMoney().subtract(send);
		user.setMoney(t);
		toUser.setMoney(toUser.getMoney().add(send));
		storeAdapter.saveUser(user);
		storeAdapter.saveUser(toUser);
		res.set(ResponseStatus.OK, user.getMoney()
				.toPlainString());
	}

	@Override
	public void withdraw(UserDTO user, Map<String, String> args, Response res) {
		BigDecimal add = BigDecimal.ZERO;
		try {
			add = new BigDecimal(args.get(OperationType.WITHDRAW.toString()));
		} catch (Exception e) {
			res.set(ResponseStatus.INVALID,
					"invalid amount specified");
			return;
		}
		if (user.getMoney().compareTo(add) < 0) {
			res.set(ResponseStatus.NOPOSSIBLE, "not enough money");
			return;
		}
		user.setMoney(user.getMoney().subtract(add));
		storeAdapter.saveUser(user);
		res.set(ResponseStatus.OK, user.getMoney()
				.toPlainString());
	}

	@Override
	public void destroy() {
		storeAdapter.destroy();
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}


}
